﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace CustomForm.Common.Extensions
{
    public static class CryptographyExtensions
    {
        private const string MD5Key = "YS03m11d!((*)#!!";

        /// <summary>
        /// MD5加密字符串（32位）
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">加密秘钥</param>
        /// <param name="upper">是否大写</param>
        /// <returns>加密后的字符串</returns>
        public static string MD5(this string source, bool upper = false)
        {
            using var md5 = new MD5CryptoServiceProvider();
            byte[] buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(MD5Key + source + MD5Key));

            #region StringBuilder

            //var sb = new StringBuilder();
            //for (int i = 0; i < buffer.Length; i++)
            //{
            //    sb.Append(buffer[i].ToString("x2"));
            //}
            //string result = sb.ToString();

            #endregion

            // BitConverter转换出来的字符串会在每个字符中间产生一个分隔符
            string result = BitConverter.ToString(buffer).Replace("-", "");

            return upper ? result.ToUpper() : result;
        }

        /// <summary>
        /// MD5加密字符串（16位）
        ///    即取中间 16 位：9 ~ 25
        /// </summary>
        /// <param name="source">源字符串</param>
        /// <param name="key">加密秘钥</param>
        /// <param name="upper">是否大写</param>
        /// <returns>加密后的字符串</returns>
        public static string ShortMD5(this string source, bool upper = false)
        {
            using var md5 = new MD5CryptoServiceProvider();
            byte[] buffer = md5.ComputeHash(Encoding.UTF8.GetBytes(MD5Key + source + MD5Key));

            #region StringBuilder

            //var sb = new StringBuilder();
            //for (int i = 0; i < buffer.Length; i++)
            //{
            //    sb.Append(buffer[i].ToString("x2"));
            //}
            //string result = sb.ToString().Substring(8, 16);

            #endregion

            // BitConverter转换出来的字符串会在每个字符中间产生一个分隔符
            string result = BitConverter.ToString(buffer, 4, 8).Replace("-", "");

            return upper ? result.ToUpper() : result;
        }
    }
}
